package com.ruoyi.energy.service.impl;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.exception.CustomException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.energy.domain.NyTrans;
import com.ruoyi.energy.domain.NyTransAllow;
import com.ruoyi.energy.domain.NyTransAllowDetail;
import com.ruoyi.energy.domain.NyTransPart;
import com.ruoyi.energy.domain.vo.NyTransAllowDetailVO;
import com.ruoyi.energy.mapper.NyTransAllowMapper;
import com.ruoyi.energy.service.INyTransAllowService;
import com.ruoyi.energy.service.INyTransService;
import com.ruoyi.system.api.RemoteBmCodeService;
import com.ruoyi.system.api.domain.RemoteSysBmType;
import com.ruoyi.system.api.enums.SysBmCodeTypeValue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 箱变容量申请Service业务层处理
 *
 * @author cjie
 * @date 2022-03-05
 */
@Service
@Slf4j
public class NyTransAllowServiceImpl implements INyTransAllowService {
    @Autowired
    private NyTransAllowMapper nyTransAllowMapper;

    @Autowired
    private INyTransService nyTransService;

    @Autowired
    private RemoteBmCodeService remoteBmCodeService;

    /**
     * 查询箱变容量申请
     *
     * @param id 箱变容量申请ID
     * @return 箱变容量申请
     */
    @Override
    public NyTransAllow selectNyTransAllowById(String id) {
        return nyTransAllowMapper.selectNyTransAllowById(id);
    }

    /**
     * 查询箱变容量申请列表
     *
     * @param nyTransAllow 箱变容量申请
     * @return 箱变容量申请
     */
    @Override
    public List<NyTransAllow> selectNyTransAllowList(NyTransAllow nyTransAllow) {
        return nyTransAllowMapper.selectNyTransAllowList(nyTransAllow);
    }

    @Override
    public List<NyTransAllowDetailVO> selectNyTransAllowDetailVOList(NyTransAllow nyTransAllow) {
        return nyTransAllowMapper.selectNyTransAllowDetailVOList(nyTransAllow);
    }

    /**
     * 新增箱变容量申请
     *
     * @param nyTransAllow 箱变容量申请
     * @return 结果
     */
    @Transactional
    @Override
    public int insertNyTransAllow(NyTransAllow nyTransAllow) {
        nyTransAllow.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
        nyTransAllow.setCreateTime(DateUtils.getNowDate());
        nyTransAllow.setCreateBy(SecurityUtils.getUsername());
        int rows = nyTransAllowMapper.insertNyTransAllow(nyTransAllow);
        insertNyTransAllowDetail(nyTransAllow);
        return rows;
    }

    /**
     * 修改箱变容量申请
     *
     * @param nyTransAllow 箱变容量申请
     * @return 结果
     */
    @Transactional
    @Override
    public int updateNyTransAllow(NyTransAllow nyTransAllow) {
        nyTransAllow.setUpdateTime(DateUtils.getNowDate());
        nyTransAllow.setUpdateBy(SecurityUtils.getUsername());
        nyTransAllowMapper.deleteNyTransAllowDetailByAllowId(nyTransAllow.getId());
        insertNyTransAllowDetail(nyTransAllow);
        return nyTransAllowMapper.updateNyTransAllow(nyTransAllow);
    }

    /**
     * 批量删除箱变容量申请
     *
     * @param ids 需要删除的箱变容量申请ID
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteNyTransAllowByIds(String[] ids) {
//        nyTransAllowMapper.deleteNyTransAllowDetailByAllowIds(ids);
//        return nyTransAllowMapper.deleteNyTransAllowByIds(ids);
        return nyTransAllowMapper.deleteNyTransAllowDetailByIds(ids);
    }

    /**
     * 删除箱变容量申请信息
     *
     * @param id 箱变容量申请ID
     * @return 结果
     */
    @Override
    public int deleteNyTransAllowById(String id) {
        nyTransAllowMapper.deleteNyTransAllowDetailByAllowId(id);
        return nyTransAllowMapper.deleteNyTransAllowById(id);
    }

    @Override
    public String importData(List<NyTransAllowDetailVO> buiRoomVOList, String meterType) {
        if (StringUtils.isNull(buiRoomVOList) || buiRoomVOList.size() == 0) {
            throw new CustomException("导入抄表数据不能为空！");
        }
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        buiRoomVOList = buiRoomVOList.stream().filter(o->StringUtils.isNotBlank(o.getEnName())).collect(Collectors.toList());
        this.insertDataBatch(buiRoomVOList,meterType);
        successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + buiRoomVOList.size() + " 条，数据如下：");
        return successMsg.toString();
    }

    @Override
    public Map<String, List<NyTransAllowDetailVO>> selectNyTransAllowDetailVOListByTransId(String transId) {
        NyTransAllow nyTransAllow = new NyTransAllow();
        nyTransAllow.setTransId(transId);
        List<NyTransAllowDetailVO> list = this.selectNyTransAllowDetailVOList(nyTransAllow);
        return list.stream().collect(Collectors.groupingBy(NyTransAllowDetailVO::getEnName));
    }

    //批量插入数据
    private void insertDataBatch(List<NyTransAllowDetailVO> buiRoomVOList, String meterType){
        //查询 NyTransAllow ,不存在 插入
        //查询箱变列表，HashMap
        Map<String, NyTransAllow> nyTransMap = this.selectNyTransAllowList(new NyTransAllow()).stream().collect(Collectors.toMap(o->(o.getEnName()+o.getTransName()), a->a));
        NyTransAllowDetail target = new NyTransAllowDetail();
        NyTransPart search = new NyTransPart();
        for ( NyTransAllowDetailVO vo1: buiRoomVOList) {
            BeanUtils.copyBeanProp(target,vo1);
            //检查数据
            if(StringUtils.isBlank(vo1.getParkNum())){
                throw new CustomException("园区编号不能为空");
            }
            if(StringUtils.isBlank(vo1.getTransName())){
                //throw new CustomException("变压器名称不能为空");
                log.info("变压器名称为空,跳过");
                continue;
            }

            if(nyTransMap.get(vo1.getEnName()+vo1.getTransName()) != null){
                target.setAllowId(nyTransMap.get(vo1.getEnName()+vo1.getTransName()).getId());
            }else{
                //insert Allow
                NyTransAllow allow = new NyTransAllow();
                allow.setEnName(vo1.getEnName());
                allow.setTransName(vo1.getTransName());
                allow.setAllow(vo1.getAllow());
                NyTrans nyTrans = nyTransService.selectNyTransByName(vo1.getTransName(),vo1.getParkNum());
                if(nyTrans != null){
                    allow.setTransId(nyTrans.getId().toString());
                }else {
                    nyTrans = new NyTrans();
                    nyTrans.setName(vo1.getTransName());
                    nyTrans.setParkNum(vo1.getParkNum());
                    String genCode = vo1.getParkNum() + "-01-01-09";
                    RemoteSysBmType bmType = remoteBmCodeService.getCodeByGenCode(genCode, SysBmCodeTypeValue.DEVICE);
                    nyTrans.setNum(bmType.getNowCode());
                    nyTransService.insertNyTrans(nyTrans);
                    allow.setTransId(nyTrans.getId().toString());
                }
                this.insertNyTransAllow(allow);
                //map put
                nyTransMap.put(allow.getEnName()+allow.getTransName(),allow);
                target.setAllowId(allow.getId());
            }
            target.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
            nyTransAllowMapper.insertNyTransAllowDetail(target);
        }
    }

    /**
     * 新增箱变容量申请详情信息
     *
     * @param nyTransAllow 箱变容量申请对象
     */
    public void insertNyTransAllowDetail(NyTransAllow nyTransAllow) {
        List<NyTransAllowDetail> nyTransAllowDetailList = nyTransAllow.getNyTransAllowDetailList();
        String id = nyTransAllow.getId();
        if (StringUtils.isNotEmpty(nyTransAllowDetailList)) {
            List<NyTransAllowDetail> list = new ArrayList<NyTransAllowDetail>();
            for (NyTransAllowDetail nyTransAllowDetail : nyTransAllowDetailList){
                //插入
                if(StringUtils.isBlank(nyTransAllowDetail.getId())){
                    nyTransAllowDetail.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
                    nyTransAllowDetail.setAllowId(id);
                }//更新
                list.add(nyTransAllowDetail);
            }
            if (list.size() > 0) {
                nyTransAllowMapper.batchNyTransAllowDetail(list);
            }
        }
    }
}
